package dbops

import (
	_ "github.com/go-sql-driver/mysql" //匿名导入
	"gitee.com/Cookie_XiaoD/video_server/api/defs"
	"strconv"
	"sync"
	"log"
)

func InsertSeesion(sid string, ttl int64, uname string) error {
	ttlstr := strconv.FormatInt(ttl, 10)
	log.Println("准备保存的ttl:"+ttlstr)
	stmtins, err := dbConn.Prepare("INSERT INTO sys_session(session_id,ttl,login_name) VALUES(?,?,?)")
	defer stmtins.Close()
	if err != nil {
		return err
	}
	if _, err = stmtins.Exec(sid, ttlstr, uname); err != nil {
		return err
	}
	return nil
}

func RetrieveSession(sid string) (session *defs.SimpleSession, err error) {
	stmtOut, err := dbConn.Prepare("SELECT ttl,login_name FROM sys_session WHERE session_id=?")
	defer stmtOut.Close()
	if err != nil {
		return
	}

	var (
		ttlstr    string
		loginName string
	)

	if err = stmtOut.QueryRow(sid).Scan(&ttlstr, &loginName); err != nil {
		return
	}


	ttl, err := strconv.ParseInt(ttlstr, 10, 64)
	if err!=nil{
		return
	}

	session = &defs.SimpleSession{
		TTL:      ttl,
		Username: loginName,
	}

	return
}

func RetrieveAllSessions() (result *sync.Map,err error) {
	stmtOut,err:=dbConn.Prepare("SELECT * FROM sys_session")
	if err!=nil{
		return
	}
	rows,err:=stmtOut.Query()
	if err!=nil{
		return
	}
	result=&sync.Map{}

	for rows.Next(){
		var(
			sessionId string
			ttl int64
			login_name string
		)
		if err=rows.Scan(&sessionId,&ttl,&login_name);err!=nil{
			return
		}
		ss:=&defs.SimpleSession{
			TTL:ttl,
			Username:login_name,
		}
		result.Store(sessionId,ss)
	}


	return
}

func DelSession(sid string)error{
	stmt,err:=dbConn.Prepare("DELETE FROM sys_session WHERE session_id=?")
	if err!=nil{
		return err
	}

	if _,err=stmt.Exec(sid);err!=nil{
		return err
	}


	return nil
}
